package com.lizicloud.user.userLogin.controller;

import com.lizicloud.application.dto.ApiResponse;
import com.lizicloud.user.userLogin.constants.LoginConstants;
import com.lizicloud.user.userLogin.dto.LoginDTO;
import com.lizicloud.user.userLogin.dto.LoginResponse;
import com.lizicloud.user.userLogin.service.UserService;
import com.lizicloud.user.userRegister.dto.RegisterDTO;
import com.lizicloud.user.userRegister.service.RegisterService;
import com.lizicloud.infrastructure.common.utils.JwtUtils;
import com.lizicloud.infrastructure.persistence.UserMapper;
import com.lizicloud.domain.model.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 认证控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
@Tag(name = "认证管理", description = "用户登录、退出等认证相关接口")
public class AuthController {
    
    private final UserService userService;
    private final RegisterService registerService;
    private final JwtUtils jwtUtils;
    private final PasswordEncoder passwordEncoder;
    private final UserMapper userMapper;
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "用户使用用户名和密码登录系统")
    public ApiResponse<LoginResponse> login(@Validated @RequestBody LoginDTO loginDTO, 
                                            HttpServletRequest request) {
        log.info("用户登录请求：用户账号={}", loginDTO.getUseraccount());
        return userService.login(loginDTO, request);
    }
    
    /**
     * 测试密码加密和验证
     */
    @PostMapping("/test-password")
    public ApiResponse<String> testPassword(@RequestBody LoginDTO loginDTO) {
        String plainPassword = loginDTO.getPassword();
        log.info("原始密码: {}", plainPassword);
        
        // 加密密码
        String encodedPassword = passwordEncoder.encode(plainPassword);
        log.info("加密后密码: {}", encodedPassword);
        log.info("密码长度: {}", encodedPassword.length());
        log.info("是否以$2a$开头: {}", encodedPassword.startsWith("$2a$"));
        
        // 验证密码
        boolean matches = passwordEncoder.matches(plainPassword, encodedPassword);
        log.info("密码验证结果: {}", matches);
        
        return ApiResponse.success("密码测试成功，加密结果: " + encodedPassword.substring(0, 20) + "...");
    }
    
    /**
     * 重置管理员密码（仅用于测试）
     */
    @PostMapping("/reset-admin-password")
    public ApiResponse<String> resetAdminPassword(@RequestBody LoginDTO loginDTO) {
        try {
            // 加密密码
            String encodedPassword = passwordEncoder.encode(loginDTO.getPassword());
            log.info("重置管理员密码，新密码加密后: {}", encodedPassword);
            
            // 查询管理员用户
            User user = userMapper.selectByUseraccount("admin001");
            if (user == null) {
                return ApiResponse.error("管理员用户不存在");
            }
            
            // 更新密码
            user.setPassword(encodedPassword);
            userMapper.updateById(user);
            
            return ApiResponse.success("管理员密码重置成功");
        } catch (Exception e) {
            log.error("重置管理员密码失败: {}", e.getMessage());
            return ApiResponse.error("重置管理员密码失败");
        }
    }
    
    /**
     * 用户注册
     */
    @PostMapping("/register")
    @Operation(summary = "用户注册", description = "新用户注册账号")
    public ApiResponse<String> register(@Validated @RequestBody RegisterDTO registerDTO) {
        log.info("用户注册请求：用户账号={}", registerDTO.getUseraccount());
        return registerService.register(registerDTO);
    }
    
    /**
     * 获取当前用户信息
     */
    @GetMapping("/userinfo")
    @Operation(summary = "获取用户信息", description = "获取当前登录用户的信息")
    public ApiResponse<LoginResponse.UserInfo> getUserInfo(@RequestHeader("Authorization") String authorization) {
        try {
            // 从Authorization头中提取token
            String token = extractToken(authorization);
            if (token == null) {
                return ApiResponse.error(LoginConstants.INVALID_TOKEN_MESSAGE);
            }
            
            // 解析token获取用户名
            String username = jwtUtils.getUsernameFromToken(token);
            if (username == null) {
                return ApiResponse.error(LoginConstants.INVALID_TOKEN_MESSAGE);
            }
            
            // 调用userService获取用户信息
            return userService.getUserInfo(username);
            
        } catch (Exception e) {
            log.error("获取用户信息失败：错误={}", e.getMessage());
            return ApiResponse.error("获取用户信息失败");
        }
    }
    
    /**
     * 用户退出
     */
    @PostMapping("/logout")
    @Operation(summary = "用户退出", description = "用户退出登录")
    public ApiResponse<String> logout(@RequestHeader("Authorization") String authorization) {
        try {
            // 从Authorization头中提取token
            String token = extractToken(authorization);
            if (token != null) {
                log.info("用户退出登录");
                // 实际项目中可以在这里处理token的失效逻辑
            }
            
            return ApiResponse.success(LoginConstants.LOGOUT_SUCCESS_MESSAGE);
            
        } catch (Exception e) {
            log.error("用户退出失败：错误={}", e.getMessage());
            return ApiResponse.error("退出失败");
        }
    }
    
    /**
     * 从Authorization头中提取token
     */
    private String extractToken(String authorization) {
        if (authorization != null && authorization.startsWith(LoginConstants.TOKEN_PREFIX)) {
            return authorization.substring(LoginConstants.TOKEN_PREFIX.length());
        }
        return null;
    }
}